import { Component, error, EventHandler, Label, _decorator } from 'cc';
import CountTimeUnit from './CountTimeUnit';
import VMBase from './VMBase';

//todo

// +普通 label 更新数据的情况,label.string = xxx;
// +frameIndex 插件，通过number 数值设置 BhvFrameIndex 来切换当前贴图
// +spriteFrame 直接替换贴图的情况 , 
//  读取本地路径 data.spriteFrame = $res:/pic/com1
//  读取网页路径 data.spriteFrame = $url:http:xxxxxxxxxx.png
// +特殊条件控制 

// 比较条件:,如果传入值 > /< />= /<= /== 某值时，执行的action类型

const {ccclass, property,executeInEditMode,menu,help} = _decorator;

// enum WatchMode {
//     ccLabel,
//     ccRichText,
//     ccSlider,
//     ccProgressBar,
// }

enum FILTER_MODE {
    "none",
    "==", //正常计算，比较 等于
    "!=", //正常计算，比较 不等于
    ">",  //正常计算，比较>
    ">=", //正常计算，比较>=
    "<",  //正常计算，比较<
    "<=", // 正常计算，比较>=
}

/**
 *  [VM-Event]
 * 提供  ViewModel 的相关基础功能,
 * 如果值发生变化将会调用对应的函数方法
 */
@ccclass("VMCountDown")
@executeInEditMode
@menu('ModelViewer/VM-CountDown(倒计时)')
@help('https://github.com/wsssheep/cocos_creator_mvvm_tools/blob/master/docs/VMEvent.md')
export default class VMCountDown extends VMBase {
    @property({
        tooltip:'监听获取值的路径',
    })
    watchPath:string = "";

    @property({
        tooltip:'设置倒计时剩余时间,非必填',
    })
    countDownSetPath:string = "";

    @property([EventHandler])
    overEvents:EventHandler[] = [];

    private timer:CountTimeUnit = new CountTimeUnit();

    originText = "";

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        super.onLoad();
        this.checkLabel();
        this.originText = this.getComponent(Label).string;
    }

    async onValueInit(){
        this.timer.clear();
        this.timer.start(()=>{
            this.updateTimer();
        },1000);
        this.updateTimer();
    }
    updateTimer(){
        let value = this.VM.getValue(this.watchPath);
        let cha = value-new Date().getTime();
        cha = Math.floor(cha/1000);
        var regexAll = /\{\{(.+?)\}\}/g;
        let arr = this.originText.match(regexAll);
        let result = this.originText;
        for (const val of arr) {
            result = result.replace(val,cha+"");
        }
        this.getComponent(Label).string = result;

        if(cha == 0)
        {
            if(Array.isArray(this.overEvents)){
                this.overEvents.forEach(v=>{
                    v.emit([]);
                })
            }
        }
        
        if(this.countDownSetPath == "")return;
        this.VM.setValue(this.countDownSetPath,cha);
    }
    
    onValueChanged(newVar:any,oldVar:any,pathArr:any[]){
        this.updateTimer();
    }
   

    checkLabel() {
        let checkArray = [
            'cc.Label'
        ];
        for (let i = 0; i < checkArray.length; i++) {
            const e = checkArray[i];
            let comp = this.node.getComponent(e);
            if (comp) {
                return true;
            }

        }
        error('没有挂载任何label组件');
        return false;

    }
    onDestroy(){
        this.timer.clear();
    }

    // update (dt) {}
}

